﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;
using ZX.BPM.Library;
using ZX.EHR.Library;
using ZX.BLL;
using ZX.Common;
using System.Text;
using System.Collections;
using System.Data;
using ZX.BLL.ClientMobi.Message;

namespace ZX.WebApp.Mobi.proc
{
    /// <summary>
    /// GetData 的摘要说明
    /// </summary>
    /// 
    public class GetData : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        DatUser user = new DatUser();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string type = context.Request["TYPE"];
            string para = System.Web.HttpUtility.UrlDecode(context.Request["PARA"]);
            if (HttpContext.Current.Session["User"] != null)
            {
                user = (DatUser)HttpContext.Current.Session["User"];
                context.Response.Write(Proc(type, para));
            }
            else if (type == "GetUser1")
            {//yonghuyanzheng
                context.Response.Write(GetUser(para));
            }
            else
            {
                context.Response.Write("@@N*L@@");
            }
        }
        private string Proc(string type, string para)
        {
            string back = "";
            switch (type)
            {
                case "GetTaskCount":
                    back = GetTaskCount();
                    break;
                case "UnLoad":
                    back = UnLoad();
                    break;
                case "GetTask":
                    back = GetTask(para);
                    break;
                case "LoadDeptTree":
                    back = (new ZX.Web.UI.Controls.TreeView()).createTreeHtml("@001-001");
                    break;
                case "GetUser":
                    back = GetUser(para);
                    break;
                case "GetWFList":
                    back = GetWFList(para);
                    break;
                case "GetWFItem":
                    back = GetWFItem(para);
                    break;
                case "GetWFItemList":
                    back = GetWFItemList(para);
                    break;
                case "ModifyPassword":
                    back = ModifyPassword(para);
                    break;
                case "GetMSGList":
                    back = GetMSGList(para);
                    break;
                case "GetMSGListCount":
                    back = GetMSGListCount(para);
                    break;
                case "SetMSGYD":
                    back = SetMSGYD(para);
                    break;
                case "MoveNext":
                    back = MoveNext(para);
                    break;
                case "WorkFlowInstanceId":
                    back = ModifyWFIStatus(para);
                    break;
                //通讯录部门
                case "GetTXLBMItems":
                    back = GetTXLBMItems(para);
                    break;
                //通讯录人员
                case "GetTXLItems":
                    back = GetTXLItems(para);
                    break;
                case "GetDeptName":
                    back = GetDeptName(para);
                    break;
                case "WorkFlowApproveViewItems":
                    back = WorkFlowApproveViewItems(para);
                    break;
                case "Exec_OperatorBack":
                    back = Exec_OperatorBack(para);
                    break;
                //全部设为已读
                case "SetAllYD":
                    back = SetAllYD(para);
                    break;
                //员工风采
                case "DatMessageQueue":
                    back = DatMessageQueue(para);
                    break;
                //培训资料
                case "PxzlDataList":
                    back = PxzlDataList(para);
                    break;
                //消息分类列表
                case "MSGSort":
                    back = MSGSortList(para);
                    break;
                case "GetUserQuanXian":
                    back = GetUserQuanXian();
                    break;
                //反馈列表
                case "MSGReply":
                    back = GetMSGReply(para);
                    break;
                //反馈列表权限 
                case "fkjyRule":
                    back = fkjyRuleList(para);
                    break;
            }
            return back;
        }

        /// <summary>
        /// 通过webServer获得token
        /// </summary>
        /// <returns></returns>
        public string GetToken()
        {
            InsideAKDService.Service1Client ws = new InsideAKDService.Service1Client();
            return ws.CheckTokenTime("5C05BA7B2C194318BA9631D92F32AEF5");

        }

        /// <summary>
        /// 查看员工是否有权限
        /// </summary>
        /// <returns>error：查询的手机号码为空或错误；有权限：【OK|{加密串}】,无权限：NO</returns>
        private string GetUserQuanXian()
        {
            string Mobile = "";
            if (HttpContext.Current.Session["MobileUserID"] != null && HttpContext.Current.Session["MobileUserID"].ToString() != "")
            {
                return "OK";
            }

            //获得手机号码
            Mobile = (new BHF_TaskInstanceView()).GetUserPhone(user.UserID.ToString());
            ///判断获得的手机号码是否有效
            if (string.IsNullOrEmpty(Mobile))
            {
                return "NO";
            }

            //调用webserver，判断该用户是否有低价本的权限
            InsideAKDService.Service1Client ws = new InsideAKDService.Service1Client();
            //有权限：【OK|加密串】,无权限：NO     OK|tuii   
            string md5UserID = ws.GetUersDate(Mobile);

            if (md5UserID.IndexOf("OK|") == 0)
            {
                string userID = md5UserID.Replace("OK|", "");
                HttpContext.Current.Session["MobileUserID"] = userID;
            }
            else
            {
                return "NO";
            }

            return "OK";

        }
        //获取待办总数
        private string GetTaskCount()
        {
            return (new BHF_TaskInstanceView()).GetTaskInstanceCount("", "", user.LoginName, 0, 20).ToString();
        }

        /// <summary>
        //  可发起的流程
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public string GetWFList(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetWFList(user.LoginName));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public string GetWFItem(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetWFItem(user.LoginName));
        }

        public string GetWFItemList(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetWFItemList(user.LoginName));
        }
        public string ModifyPassword(string newPassword)
        {
            user.Password = newPassword.GetMd5Hash();
            ZX.BLL.BUser buser = new BUser();
            buser.entity = user;
            buser.Update();
            return "OK";
        }

        //获取待办
        private string GetTask(string para)
        {
            string[] p = para.Split('︾');
            string selectname = "";
            int firs = Convert.ToInt32(p[0]);
            int size = Convert.ToInt32(p[1]);
            if (p.Length > 2)
            {
                selectname = p[2].ToString();
            }
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetTaskDatatable("", selectname, user.LoginName, firs, size));
        }

        //获取消息
        private string GetMSGList(string para)
        {
            IDictionary<string, object> diction = new Dictionary<string, object>();

            StringBuilder sqlWhereText = new StringBuilder();
            string[] paramArr = para.Split('|');
            if (paramArr.Length >= 3)
            {
                bool isdays_tsql = false;
                for (int i = 0; i < paramArr.Length; i++)
                {
                    if (i == 0)
                    {
                        if (!string.IsNullOrEmpty(paramArr[i]))
                        {
                            int day = 0;
                            int.TryParse(paramArr[i], out day);
                            {
                                isdays_tsql = true;
                            }
                            sqlWhereText.Append(" and DATEDIFF(DD, d.createDate, GETDATE())<=" + day + "");
                        }
                    }

                    if (i == 1)
                    {
                        var tempMsgStart = paramArr[i];
                        switch (tempMsgStart)
                        {
                            //未读
                            case "0":
                                {
                                    sqlWhereText.Append(" and i.readDate is null");
                                } break;
                            //已读 
                            case "1":
                                {
                                    sqlWhereText.Append(" and i.readDate is not null");
                                } break;
                            case "2": { } break; //搜索
                        }
                    }
                    if (i == 2)
                    {
                        string SearchValue = paramArr[i].ToString();
                        if (string.IsNullOrEmpty(SearchValue) && isdays_tsql == false)
                        {
                            sqlWhereText.Append(" and DATEDIFF(DD, d.createDate, GETDATE())=0");
                        }
                        else
                        {
                            sqlWhereText.Append(" and (d.title like ''%" + paramArr[i] + "%'' or d.content like ''%" + paramArr[i] + "%'')");
                        }

                    }
                    if (i == 6)
                    {
                        int idTemp = 0;
                        int.TryParse(paramArr[i].ToString(), out idTemp);
                        sqlWhereText.Append(" and (isnull(d.Classify, 0)=" + idTemp + " or (case d.Classify when 1 then 99 when 15 then 99 end)=" + idTemp + "     )");

                    }
                    if (i == 3)
                    {
                        diction.Add("pageIndex", Convert.ToInt32(paramArr[i]));

                    }
                    if (i == 4)
                    {
                        diction.Add("pageSize", Convert.ToInt32(paramArr[i]));
                    }
                    if (i == 5)
                    {
                        diction.Add("isCount", paramArr[i]);
                    }


                }
            }
            else
            {
                sqlWhereText.Append((para != "" && para != null) ? "  and d.ID=''" + para + "''" : "");
            }

            diction.Add("LoginName", user.LoginName);
            diction.Add("WhereParams", sqlWhereText.ToString());

            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetMSGList(diction));
        }

        //我的消息反馈列表
        private string GetMSGReply(string para)
        {
            IList<DatSysNewsMonthInfo> msgList = new List<DatSysNewsMonthInfo>();

            IDictionary<string, object> diction = new Dictionary<string, object>();

            StringBuilder sqlWhereText = new StringBuilder();
            #region MyRegion
            string[] paramArr = para.Split('|');
            if (paramArr.Length >= 3)
            {
                for (int i = 0; i < paramArr.Length; i++)
                {
                    if (i == 0)
                    {
                        diction.Add("pageIndex", Convert.ToInt32(paramArr[i]));

                    }
                    if (i == 1)
                    {
                        diction.Add("pageSize", Convert.ToInt32(paramArr[i]));
                    }
                    if (i == 2)
                    {
                        diction.Add("isCount", paramArr[i]);
                    }

                }
            }

            diction.Add("UserID", user.UserID);
            diction.Add("WhereParams", sqlWhereText.ToString());
            #endregion


            DatSysNewsMonthInfo msgInstance = new DatSysNewsMonthInfo();
            DataTable tabTemp = (new BHF_TaskInstanceView()).GetMSGReply(diction);
            if (tabTemp != null && tabTemp.Rows.Count>0)
            {
                //分页参数返回
                if (tabTemp.Columns.Contains("cx"))
                {
                    return "[{\"cx\": " + tabTemp .Rows[0]["cx"].ToString()+ "}]";
                }
                DataTable tabtwo = new DataTable();
                foreach (DataRow item in tabTemp.Rows)
                {
                    msgInstance = DatSysNewsMonthInfo.PopulateFromDataRow(item);
                    
                    //add MsgReply
                    IList<MsgReplyInfo> listone = new List<MsgReplyInfo>();
                    tabtwo = (new BHF_TaskInstanceView()).GetMSGReply_List(msgInstance.ID) as DataTable;
                    if (tabtwo != null && tabtwo.Rows.Count > 0)
                    {
                        //计量
                        msgInstance.ChildCX = tabtwo.Rows.Count;
                        foreach (DataRow item1 in tabtwo.Rows)
                        {
                            MsgReplyInfo infoitem1 = MsgReplyInfo.PopulateFromDataRow(item1);
                            listone.Add(infoitem1);
                        }

                    }
                    msgInstance.MsgReplyInstance = listone;
                    msgList.Add(msgInstance);
                }
                msgInstance = null;

            }

            return JsonConvert.SerializeObject(msgList);

        }

        //消息反馈权限 
        private string fkjyRuleList(string para)
        {
            DataTable tableTemp = null;
            tableTemp = (new BHF_TaskInstanceView()).fkjyRuleList(user.UserID.ToString()) as DataTable;

            if (tableTemp != null && tableTemp.Rows.Count > 0)
            {
                return "1";
            }
            return "0";
            //return JsonConvert.SerializeObject();
        }

        //获取上一条/下一条的ID
        private string MoveNext(string para)
        {

            IDictionary<string, object> diction = new Dictionary<string, object>();

            StringBuilder sqlWhereText = new StringBuilder();


            string returnResults = "";
            string[] arr = para.Split('|');
            if (arr.Length >= 3)
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i == 0)
                    {
                        diction.Add("recordID", arr[i]);
                    }
                    if (i == 1)
                    {
                        var tempMsgStart = arr[i];
                        switch (tempMsgStart)
                        {
                            //未读
                            case "0":
                                {
                                    sqlWhereText.Append(" and i.readDate is null");
                                } break;
                            //已读 
                            case "1":
                                {
                                    sqlWhereText.Append(" and i.readDate is not null");
                                } break;
                            case "2": { } break; //搜索
                        }
                    }
                    if (i == 2)
                    {
                        sqlWhereText.Append(" and (d.title like '%" + arr[i] + "%' or d.content like '%" + arr[i] + "%')");
                    }
                    if (i == 3)
                    {
                        int idTemp = 0;
                        int.TryParse(arr[i].ToString(), out idTemp);
                        sqlWhereText.Append(" and isnull(d.Classify, 0)=" + idTemp);
                    }
                    if (i == 4)
                    {
                        string dictionAction = arr[i];
                        if (dictionAction == "prev")
                        {
                            sqlWhereText.Append(" and d.createDate>@cd order by d.createDate asc");

                        }
                        else if (dictionAction == "next")
                        {

                            sqlWhereText.Append(" and d.createDate<@cd order by d.createDate desc");
                        }

                    }

                }


            }

            diction.Add("LoginName", user.LoginName);
            diction.Add("WhereParams", sqlWhereText.ToString());

            returnResults = JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetMoveNextData(diction));
            return returnResults;
        }

        //消息分类列表
        private string MSGSortList(string para)
        {

            IDictionary<string, System.Data.DataTable> DictionaryList = new Dictionary<string, System.Data.DataTable>();

            ZX.BLL.ClientMobi.Message.MessageBusiness<ZX.BLL.ClientMobi.Message.Code_BaseInfoInfo> MB = new BLL.ClientMobi.Message.MessageBusiness<BLL.ClientMobi.Message.Code_BaseInfoInfo>();

            IList<BLL.ClientMobi.Message.Code_BaseInfoInfo> listClass1 = new List<BLL.ClientMobi.Message.Code_BaseInfoInfo>();
            IList<BLL.ClientMobi.Message.Code_BaseInfoInfo> listClass2 = new List<BLL.ClientMobi.Message.Code_BaseInfoInfo>();

            string[] questParamsplit = para.Split('|');
            IDictionary<string, object> dictionary = new Dictionary<string, object>();
            if (questParamsplit.Length > 1)
            {
                try
                {
                    dictionary.Add("ClassName", questParamsplit[0]);
                    dictionary.Add("WhereSqlParams", ((questParamsplit[1] != "") ? " and x.PhraseText like ''%" + questParamsplit[1] + "%''" : " "));
                }
                catch (Exception)
                {

                    dictionary.Add("ClassName", "");
                    dictionary.Add("WhereSqlParams", " and x.PhraseText like ''%%''");
                }
            }

            dictionary.Add("pageIndex", 1);
            dictionary.Add("pageSize", 99999);
            dictionary.Add("isCount", '0');
            dictionary.Add("LoginName", user.LoginName);

            var dataSet = (new BHF_TaskInstanceView()).MSGSortList(dictionary) as DataSet;
            if (dataSet != null)
            {
                if (dataSet.Tables.Count == 2)
                {
                    DictionaryList.Add("一级分类", dataSet.Tables[0]);
                    DictionaryList.Add("二级分类", dataSet.Tables[1]);
                }
            }
            if (DictionaryList.Count > 0)
            {
                if (DictionaryList.ContainsKey("一级分类"))
                {
                    DataTable tabTemp = DictionaryList["一级分类"] as DataTable;
                    if (tabTemp != null && tabTemp.Rows.Count > 0)
                    {
                        for (int i = 0; i < tabTemp.Rows.Count; i++)
                        {
                            listClass1.Add(BLL.ClientMobi.Message.Code_BaseInfoInfo.PopulateFromDataRow(tabTemp.Rows[i]));
                        }
                    }
                }

                if (DictionaryList.ContainsKey("二级分类"))
                {
                    DataTable tabTemp = DictionaryList["二级分类"] as DataTable;
                    if (tabTemp != null && tabTemp.Rows.Count > 0)
                    {
                        for (int i = 0; i < tabTemp.Rows.Count; i++)
                        {
                            listClass2.Add(BLL.ClientMobi.Message.Code_BaseInfoInfo.PopulateFromDataRow(tabTemp.Rows[i]));
                        }
                    }
                }

                MB.ParentClas = listClass1;
                MB.childClas = listClass2;
            }

            return JsonConvert.SerializeObject(MB);
        }

        //获取消息总量
        private string GetMSGListCount(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetMSGListCount(user.LoginName));
        }

        //获取员工风采
        private string DatMessageQueue(string para)
        {
            IDictionary<string, object> diction = new Dictionary<string, object>();
            string[] paramArr = para.Split('|');
            for (int i = 0; i < paramArr.Length; i++)
            {
                if (i == 0)
                {
                    diction.Add("pageIndex", Convert.ToInt32(paramArr[i]));
                }
                if (i == 1)
                {
                    diction.Add("pageSize", Convert.ToInt32(paramArr[i]));
                }
                if (i == 2)
                {
                    diction.Add("isCount", paramArr[i]);
                }
            }

            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).DatMessageQueue(diction));
        }

        //获取培训资料
        private string PxzlDataList(string para)
        {
            IDictionary<string, object> diction = new Dictionary<string, object>();
            string[] paramArr = para.Split('|');
            StringBuilder SqlWhereParamBase = new StringBuilder();
            if (paramArr.Length > 0)
            {
                for (int i = 0; i < paramArr.Length; i++)
                {
                    if (i == 0)
                    {
                        diction.Add("ClassType", paramArr[0]);
                    }
                    if (i == 1 && !string.IsNullOrEmpty(paramArr[1]))
                    {
                        SqlWhereParamBase.AppendFormat(" and ID='{0}'", paramArr[1]);
                    }
                }

            }
            diction.Add("WhereParamBase", SqlWhereParamBase.ToString());

            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).PxzlDataList(diction));
        }


        //全部标为已读
        private string SetAllYD(string para)
        {
            string returnResults = "";
            returnResults = JsonConvert.SerializeObject((new BHF_TaskInstanceView()).SetAllYD(user.LoginName));

            return returnResults;
        }

        //设置消息已读
        private string SetMSGYD(string para)
        {

            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).SetMSGYD(user.LoginName, para));
        }

        //待办事项作废
        private string ModifyWFIStatus(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).ModifyWFIStatus(para));
        }

        //通讯录部门
        private string GetTXLBMItems(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetTXLBMItems(para));
        }

        //通讯录人员
        private string GetTXLItems(string para)
        {
            IDictionary<string, object> sqDictionaryList = new Dictionary<string, object>();
            StringBuilder whereSqlInitparam = new StringBuilder();

            if (!string.IsNullOrEmpty(para) && para.IndexOf('|') >= 0)
            {
                var paramList = para.Split('|');
                var isBool = false;
                for (int i = 0; i < paramList.Length; i++)
                {
                    switch (i)
                    {
                        case 0:
                            {
                                string parentID = paramList[i].ToString();
                                if (!string.IsNullOrEmpty(parentID))
                                {
                                    whereSqlInitparam.AppendFormat(" and DepartmentCode='{0}'", parentID);
                                }
                            } break;
                        case 1:
                            {
                                int iint = 0;
                                int.TryParse(paramList[i], out iint);
                                if (iint > 0)
                                {
                                    isBool = true;
                                    whereSqlInitparam.AppendFormat(" or dataType>0", paramList[i]);
                                }
                            } break;
                        case 2:
                            {
                                if (!isBool)
                                {
                                    whereSqlInitparam.AppendFormat(" and (CName like '%{0}%' or DepartmentName like '%{0}%' or PostNames like '%{0}%' or Name like '%{0}%' or PhoneNos like '%{0}%' or companyCornets like '%{0}%' )", paramList[i]);
                                }
                                else
                                {
                                    //领导搜索重置
                                    whereSqlInitparam.Clear();

                                    whereSqlInitparam.AppendFormat(" and (CName like '%{0}%' or DepartmentName like '%{0}%' or PostNames like '%{0}%' or Name like '%{0}%' or PhoneNos like '%{0}%' or companyCornets like '%{0}%' ) and dataType>0 ", paramList[i]);

                                }

                            }break;

                    }

                }

            }

            sqDictionaryList.Add("sqlWhereParam", whereSqlInitparam.ToString());

            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetTXLItems(sqDictionaryList));
        }

        //部门
        private string GetDeptName(string para)
        {
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetTXLItems(user.UserID.ToString()));
        }

        //我的审批列表
        private string WorkFlowApproveViewItems(string para)
        {
            string[] arr = null;
            if (string.IsNullOrEmpty(para)) return "";

            #region Old Code
            //if (para.IndexOf('|') >= 0)
            //{
            //    arr = para.Split('|');
            //}
            //return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).WorkFlowApproveViewItems(user.LoginName.ToString(), arr[0], arr[1], arr[2])); 
            #endregion

            if (para.IndexOf('|') >= 0 && para.Split('|').Length >= 4)
            {
                arr = para.Split('|');
            }
            if (arr != null)
            {
                return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).WorkFlowApproveViewItems(user.LoginName.ToString(), arr[0], arr[1], arr[2], arr[3], user.UName));
            }
            return "";


        }

        //撤销申请(退回流程)
        private string Exec_OperatorBack(string para)
        {
            string strUserLoginName = user.LoginName;
            string strWorkFlowInstanceId = para;
            var paramGroup = para.Split('|');
            if (paramGroup.Length > 1)
            {
                strWorkFlowInstanceId = paramGroup[0];
                strUserLoginName = paramGroup[1];
            }

            string Result = "";
            if (!string.IsNullOrEmpty(para))
                Result = JsonConvert.SerializeObject((new BHF_TaskInstanceView()).Exec_OperatorBack(strWorkFlowInstanceId, strUserLoginName));

            return Result;
        }

        /// <summary>
        /// 根据部门Or姓名 获取人员
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private string GetUser(string value)
        {
            string[] p = value.Split(',');
            string deptid = p[0].ToString();
            string name = null;
            if (p.Length > 1)
            {
                name = p[1].ToString();
            }
            return JsonConvert.SerializeObject((new BHF_TaskInstanceView()).GetDatUser(deptid, name));
        }


        private string UnLoad()
        {
            try
            {
                FormsAuthentication.SignOut();
                HttpContext.Current.Session["User"] = null;
                HttpContext.Current.Session["IsOutSite"] = null;
                HttpContext.Current.Session["vcode"] = null;
                return "1";
            }
            catch (Exception)
            {
                return "0";
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


    }
}
